import Vue from 'vue'
import App from './App.vue'
import 'normalize.css'
import router from './router'
import Elementui, { Form } from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import axios from '@/axios'
import jscookie from "js-cookie";
import store from '@/store'
import { Message } from 'element-ui'
import 'normalize.css'
import * as charts from 'echarts'  //按需暴露
import 'animate.css';
import Mock from '../mock'
import './filtes'

Vue.config.productionTip = false
Vue.use(Elementui)
Vue.prototype.$http = axios
Vue.prototype.$cookie = jscookie
Vue.prototype.$charts = charts


function chauser(token, next) {
  store.dispatch('chatoken', token).then((data) => {  // 验证用户信息   token是不是正确的
    store.commit('cxtoken', data.data)
    if (data.code == -1) {
      Message.error('用户凭证有误，请重新登陆')
      jscookie.remove('token')
      store.commit('removetoken')
      next('/login')
    } else {
      next()
    }
  })
}

router.beforeEach((to, from, next) => {
  // console.log(to);
  if (to.path !== '/login') {  //不去登陆页面
    if (store.state.token) {  //如果vuex有token 
      chauser(store.state.token, next)
    } else {
      let token = jscookie.get('token')
      if (token) {   //如果cookie中token  存到vuex中
        chauser(token, next)
        // store.dispatch('chatoken', jscookie.get('token')).then((data) => {  // 验证用户信息   token是不是正确的
        //   if (data.code == -1) {
        //     Message.error('用户凭证有误，请重新登陆')
        //     jscookie.remove('token')
        //     store.commit('removetoken')
        //     next('/login')
        //   } else {
        //     next()
        //   }
        // })
        store.commit('cuntoken', jscookie.get('token'))
      } else {
        next('/login')   //跳转到登陆页面
      }
    }
  } else {
    //去登陆页面
    if (store.state.token) {  //如果vuex有token 
      next('/')
      Message.error('请退出登录')
    } else {
      if (jscookie.get('token')) {   //如果cookie中token  存到vuex中
        store.commit('cuntoken', jscookie.get('token'))
        Message.error('请退出登录')
        next('/')
      } else {
        next()   //跳转到登陆页面
      }
    }

  }
})

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
